from flask import Blueprint, jsonify, request, current_app, url_for, send_from_directory
from app.models.models import db, Team, Match
from sqlalchemy import func
import os
from werkzeug.utils import secure_filename
import uuid
from itertools import groupby
from operator import itemgetter

teams = Blueprint('teams', __name__)

# 允许的图片扩展名
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@teams.route('/api/teams', methods=['GET'])
def get_teams():
    teams = Team.query.all()
    matches = Match.query.all()
    
    # 创建团队字典，用于跟踪每个队伍的比赛数和胜利次数
    teams_data = {}
    
    for team in teams:
        teams_data[team.id] = {
            'id': team.id,
            'name': team.name,
            'league': team.league,
            'game': team.game,
            'icon': url_for('static', filename=f'team_icons/{team.icon}', _external=True) if team.icon else None,
            'total_matches': 0,
            'wins': 0
        }
    
    # 基于实际比赛记录统计获胜次数和总比赛数
    for match in matches:
        # 安全地获取game_type，如果不存在就使用默认值
        game_type = getattr(match, 'game_type', 'lol') 
        
        # 主队参与比赛数+1
        if match.team1_id in teams_data:
            teams_data[match.team1_id]['total_matches'] += 1
            # 如果主队获胜，胜利次数+1
            if match.winner_id == match.team1_id:
                teams_data[match.team1_id]['wins'] += 1
        
        # 客队参与比赛数+1
        if match.team2_id in teams_data:
            teams_data[match.team2_id]['total_matches'] += 1
            # 如果客队获胜，胜利次数+1
            if match.winner_id == match.team2_id:
                teams_data[match.team2_id]['wins'] += 1
    
    # 计算胜率
    for team_id, team_data in teams_data.items():
        total_matches = team_data['total_matches']
        wins = team_data['wins']
        win_rate = 0 if total_matches == 0 else round(wins / total_matches * 100)
        team_data['win_rate'] = win_rate
    
    return jsonify(list(teams_data.values())), 200

@teams.route('/api/teams', methods=['POST'])
def create_team():
    data = request.get_json()
    team = Team(
        name=data['name'],
        league=data['league'],
        game=data['game']
    )
    db.session.add(team)
    db.session.commit()
    
    # 新创建的战队还没有比赛记录
    total_matches = 0
    wins = 0
    win_rate = 0
    
    return jsonify({
        'id': team.id,
        'name': team.name,
        'league': team.league,
        'game': team.game,
        'icon': url_for('static', filename=f'team_icons/{team.icon}', _external=True),
        'total_matches': total_matches,
        'wins': wins,
        'win_rate': win_rate
    }), 201

@teams.route('/api/teams/<int:team_id>', methods=['GET'])
def get_team(team_id):
    team = Team.query.get_or_404(team_id)
    
    # 获取实际比赛数据
    total_matches = 0
    wins = 0
    
    # 查询该队参与的所有比赛
    team1_matches = Match.query.filter_by(team1_id=team.id).all()
    team2_matches = Match.query.filter_by(team2_id=team.id).all()
    
    # 统计作为主队的记录
    for match in team1_matches:
        total_matches += 1
        if match.winner_id == team.id:
            wins += 1
    
    # 统计作为客队的记录
    for match in team2_matches:
        total_matches += 1
        if match.winner_id == team.id:
            wins += 1
    
    # 计算胜率
    win_rate = round((wins / total_matches * 100) if total_matches > 0 else 0)
    
    return jsonify({
        'id': team.id,
        'name': team.name,
        'league': team.league,
        'game': team.game,
        'icon': url_for('static', filename=f'team_icons/{team.icon}', _external=True),
        'total_matches': total_matches,
        'wins': wins,
        'win_rate': win_rate
    })

@teams.route('/api/teams/<int:team_id>', methods=['PUT'])
def update_team(team_id):
    team = Team.query.get_or_404(team_id)
    data = request.get_json()
    team.name = data.get('name', team.name)
    team.league = data.get('league', team.league)
    team.game = data.get('game', team.game)
    db.session.commit()
    
    # 获取实际比赛数据
    total_matches = 0
    wins = 0
    
    # 查询该队参与的所有比赛
    team1_matches = Match.query.filter_by(team1_id=team.id).all()
    team2_matches = Match.query.filter_by(team2_id=team.id).all()
    
    # 统计作为主队的记录
    for match in team1_matches:
        total_matches += 1
        if match.winner_id == team.id:
            wins += 1
    
    # 统计作为客队的记录
    for match in team2_matches:
        total_matches += 1
        if match.winner_id == team.id:
            wins += 1
    
    # 计算胜率
    win_rate = round((wins / total_matches * 100) if total_matches > 0 else 0)
    
    return jsonify({
        'id': team.id,
        'name': team.name,
        'league': team.league,
        'game': team.game,
        'icon': url_for('static', filename=f'team_icons/{team.icon}', _external=True),
        'total_matches': total_matches,
        'wins': wins,
        'win_rate': win_rate
    })

@teams.route('/api/teams/<int:team_id>/icon', methods=['POST'])
def upload_team_icon(team_id):
    team = Team.query.get_or_404(team_id)
    
    # 检查是否有文件被上传
    if 'icon' not in request.files:
        return jsonify({'error': '没有选择文件'}), 400
        
    file = request.files['icon']
    
    # 如果用户没有选择文件，浏览器也会发送一个空的文件
    if file.filename == '':
        return jsonify({'error': '没有选择文件'}), 400
        
    if file and allowed_file(file.filename):
        # 生成安全的文件名（使用UUID避免文件名冲突）
        filename = secure_filename(file.filename)
        ext = filename.rsplit('.', 1)[1].lower()
        new_filename = f"{uuid.uuid4().hex}.{ext}"
        
        # 保存文件
        upload_folder = os.path.join(current_app.static_folder, 'team_icons')
        os.makedirs(upload_folder, exist_ok=True)
        file_path = os.path.join(upload_folder, new_filename)
        file.save(file_path)
        
        # 删除旧图标（如果不是默认图标）
        if team.icon != 'default_team.png':
            old_icon_path = os.path.join(upload_folder, team.icon)
            if os.path.exists(old_icon_path):
                os.remove(old_icon_path)
        
        # 更新数据库
        team.icon = new_filename
        db.session.commit()
        
        # 获取实际比赛数据
        total_matches = 0
        wins = 0
        
        # 查询该队参与的所有比赛
        team1_matches = Match.query.filter_by(team1_id=team.id).all()
        team2_matches = Match.query.filter_by(team2_id=team.id).all()
        
        # 统计作为主队的记录
        for match in team1_matches:
            total_matches += 1
            if match.winner_id == team.id:
                wins += 1
        
        # 统计作为客队的记录
        for match in team2_matches:
            total_matches += 1
            if match.winner_id == team.id:
                wins += 1
        
        # 计算胜率
        win_rate = round((wins / total_matches * 100) if total_matches > 0 else 0)
        
        return jsonify({
            'id': team.id,
            'name': team.name,
            'league': team.league,
            'game': team.game,
            'icon': url_for('static', filename=f'team_icons/{team.icon}', _external=True),
            'total_matches': total_matches,
            'wins': wins,
            'win_rate': win_rate
        })
    
    return jsonify({'error': '不支持的文件类型'}), 400 